'use strict';

angular.module('angularRestfulAuth', [
    'ngStorage',
    'ngRoute',
    'ui.uploader',
    'commonDirective'
])
.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {

    $routeProvider.
        when('/', {
            templateUrl: 'partials/home.html',
            controller: 'homeCtrl'
        }).
        when('/local', {
            templateUrl: 'partials/local.html',
            controller: 'localCtrl'
        }).
        when('/remote', {
            templateUrl: 'partials/remote.html',
            controller: 'remoteCtrl'
        }).
        when('/other', {
            templateUrl: 'partials/other.html',
            controller: 'otherCtrl'
        }).
        when('/system', {
            templateUrl: 'partials/system.html',
            controller: 'systemCtrl'
        }).
        otherwise({
            redirectTo: '/'
        });

    $httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
            return {
                'request': function (config) {
                    config.headers = config.headers || {};
                    $localStorage.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NzgzMDA5MTQsIm5iZiI6MTQ3ODMwMDkxNCwiaWRlbnRpdHkiOiI4YTczYTlkOC01YTFlLTQ1NDEtODU4Ny0zMjY0ZDBiNDg4NDcifQ.fLZgxFJM8MdwIVpMOv4HKfqCqqGLtsXTaYm4mGswwc8';
                    if ($localStorage.token) {
                        config.headers.Authorization = 'Bearer ' + $localStorage.token;
                    }
                    return config;
                },
                'requestError': function (request) {
                    return request
                },
                'response': function (response) {
                    return response;
                },
                'responseError': function(response) {
                    console.log(response.headers('Access-Control-Allow-Headers'));
                    if(response.status === 401 || response.status === 403) {
                        $location.path('/signin');
                    }
                    return $q.reject(response);
                }
            };
        }]);

    }
]);